<template>
  <div class="hash-tool">
    <h2>哈希工具</h2>
    <div class="input-group">
      <label for="hashInput">输入文本：</label>
      <textarea id="hashInput" v-model="inputText" rows="4" placeholder="请输入要生成哈希的文本"></textarea>
    </div>
    <div class="input-group">
      <label for="algorithm">选择算法：</label>
      <select id="algorithm" v-model="algorithm">
        <option value="MD5">MD5</option>
        <option value="SHA1">SHA1</option>
        <option value="SHA256">SHA256</option>
      </select>
    </div>
    <button @click="generateHash">生成哈希</button>
    <div class="result" v-if="result">
      <h3>哈希结果：</h3>
      <textarea v-model="result" rows="2" readonly></textarea>
    </div>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js';

export default {
  name: "HashTool",
  data() {
    return {
      inputText: "",
      algorithm: "MD5",
      result: "",
      error: ""
    };
  },
  methods: {
    generateHash() {
      this.error = "";
      this.result = "";
      if (!this.inputText) {
        this.error = "请输入文本。";
        return;
      }
      try {
        let hash;
        if (this.algorithm === "MD5") {
          hash = CryptoJS.MD5(this.inputText);
        } else if (this.algorithm === "SHA1") {
          hash = CryptoJS.SHA1(this.inputText);
        } else if (this.algorithm === "SHA256") {
          hash = CryptoJS.SHA256(this.inputText);
        } else {
          this.error = "选择的算法无效。";
          return;
        }
        this.result = hash.toString();
      } catch (e) {
        this.error = "生成哈希时出现错误：" + e.message;
      }
    }
  }
};
</script>

<style scoped>
.hash-tool {
  max-width: 600px;
  margin: 20px auto;
  padding: 10px;
}
.input-group {
  margin: 10px 0;
}
.input-group label {
  display: block;
  margin-bottom: 5px;
}
.input-group textarea,
.input-group select {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}
button:hover {
  background-color: #2980b9;
}
.result {
  margin-top: 20px;
}
.result textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
.error {
  color: red;
  margin-top: 10px;
}
</style> 